var booksBorrowsManager;
var addNewBooksOpen;

$(function() {
	var validData = [{ valid: 1, text: '是' }, { valid: 0, text: '否'}];
	var caseData = [];
	var classfyData = [];
	for(var i in caseList){
		var inerJson = {};
		inerJson.caseid = caseList[i].id;
		inerJson.text = caseList[i].name;
		caseData.push(inerJson);
	}
	for(var i in classfyList){
		var inerJson = {};
		inerJson.classfyid = classfyList[i].id;
		inerJson.text = classfyList[i].name;
		classfyData.push(inerJson);
	}
	booksBorrowsManager = window['g'] = $("#maingrid").ligerGrid({
		height : '100%',
		url:'/v1/b/getBooks?valid=1',
		pageSize : 10,
		columns : [{
			display : '操作',
			isSort : false,
			width : 120,
			showTitle : false,
			render : function(rowdata, rowindex) {
                b = " <a  href='javascript:backBook("+rowdata.id+");'>还书</a>";
                return b;
			}
		}, {
			display : '分类',
			name : 'classfyid',
			minWidth : 50,
			align : "center",
            render: function (item)
            {
                 for(var i in classfyData){
                	 if(item.classfyid == classfyData[i].classfyid){
                		 return classfyData[i].text;
                	 }
                 }
            },
			isSort : false
		} ,{
			display : '语言',
			name : 'language',
			minWidth : 20,
			align : "center",
			isSort : false
		}, {
			display : '书名',
			name : 'bookname',
			minWidth : 50,
			align : "center",
			minWidth : 50,
		}, {
			display : '书架',
			name : 'caseid',
			minWidth : 100,
			align : "center",
            render: function (item)
            {
                 for(var i in caseData){
                	 if(item.caseid == caseData[i].caseid){
                		 return caseData[i].text;
                	 }
                 }
            },
			isSort : false
		}, {
			display : '简介',
			name : 'briefdesc',
			minWidth : 100,
			align : "center",
			isSort : false
		}, {
			display : '关键字',
			name : 'sword',
			minWidth : 60,
			align : "center",
			isSort : false
		},{
			display : '作者',
			name : 'author',
			type : 'test',
			minWidth : 50,
			align : "center",
			isSort : false
		},{
			display : '翻译',
			name : 'translator',
			minWidth : 60,
			align : "center",
			isSort : false
		},{
			display : '出版社',
			name : 'pubname',
			minWidth : 20,
			align : "center",
			isSort : false
		},{
			display : '价格',
			name : 'price',
			minWidth : 20,
			align : "center",
			isSort : false
		},{
			display : 'ISBN',
			name : 'isbn',
			minWidth : 60,
			align : "center",
			isSort : false
		},{
			display : '页数',
			name : 'length',
			minWidth : 20,
			align : "center",
			isSort : false
		},{
			display : '出版年份',
			name : 'intime',
			minWidth : 20,
			align : "center",
			isSort : false
		},{
			display : '入库日期',
			name : 'year',
			minWidth : 50,
			format : 'yyyy年MM月dd日',
			isSort : false,
			render : function(record, rowindex, value, column){
				var newDate = new Date(value);
				return newDate.format("yyyy年MM月dd日");
			}
		}],
		rownumbers : true,
		onSelectRow: function (rowdata, rowindex)
        {
           
        },
        enabledEdit: true, 
        isScroll: false, 
        rownumbers:true
	});
	
    
    jQuery("#pageloading").hide();

});
function getUpdate()
{
    var data = booksBorrowsManager.getUpdated();
    alert(JSON.stringify(data));
    return data;
}

function saveUpdateBooks(item){
	var data = booksBorrowsManager.getUpdated();
	var addData = booksBorrowsManager.getAdded();
	if(addData.length > 0){
		for(var i=0;i<addData.length;i++){
			data.push(addData[i]);
		}
	}
	if(data.length == 0){
		$.ligerDialog.warn("亲，您还未做任何修改哦!");
		return;
	}
	doSaveBooks(data);
}
function doSaveBooks(data,add){
	jQuery.ajax({
		url:'/v1/b/saveOrUpdate',
		data:{json:JSON.stringify(data)},
		dataType:'json',
		type:'post',
		success:function(data){
			if(data.sucessList.length > 0){
				$.ligerDialog.success('亲,已经保存成功!');
				tip = $.ligerDialog.tip({ title: '提示信息', content: '亲,已经保存'+data.sucessList.length+'条记录!' });
				booksBorrowsManager.loadServerData({pagesize:10});
			}else{
				tip = $.ligerDialog.tip({ title: '提示信息', content: '网络异常,没有保存成功!' });
			}
		},
		error:function(){
			$.ligerDialog.error("网络发生异常,请稍后再试!");
		}
	});
}
function itemBooksClick(item) {
	booksBorrowsManager.addRow({ 
        year: new Date(),
        valid:1
    },0);
}
function searchBooks(){
	var bookName = jQuery("#bookNameKey").val();
	if(!bookName){
		$.ligerDialog.error("请输入书名进行搜索!");
		booksBorrowsManager.loadServerData({pagesize:10});
		return;
	}
	booksBorrowsManager.loadServerData({bookName:bookName});
}

function backBook(bookId){
	reset();
	jQuery.ajax({
		url:'/v1/ub/getBacksInfo/'+bookId,
		dataType:'json',
		type:'post',
		success:function(data){
			if(data.msg){
				$.ligerDialog.error(data.msg);
			}else{
				var user = data.user;
				var book = data.book;
				var borrow = data.borrow;
				var penalty = data.penalty;
				jQuery("#newBookId").val(bookId);
				jQuery("#newUserId").val(user.id);
				
				jQuery("#newName").html(user.name);
				jQuery("#newIdcard").html(user.idcard);
				jQuery("#newBookName").html(book.bookname);
				jQuery("#newPrice").html(book.price);
				jQuery("#newBorrowDate").html(getTime_ToStr(borrow.borrowtime));
				jQuery("#newPlanDate").html(getTime_ToStr(borrow.plantime));
				
				if(penalty){
					jQuery("#ispenalty").attr("checked","true");
					jQuery("#penaltyPrice").html(penalty.penaltyamount);
					jQuery("#penaltyReason").val("1");
				}
				
				jQuery("#penaltyReason").change(function(){
					var val = $("#penaltyReason").val();
					if(2 == val){
						jQuery("#penaltyPrice").html(book.price);
					}else if(1 == val){
						jQuery("#penaltyPrice").html(penalty.penaltyamount);
					}else{
						jQuery("#penaltyPrice").html("0");
					}
				})
				
				addBackBooksOpen = $.ligerDialog.open({ target: $("#OpenDiv") });
				
				
			}
		}
	})
	
}

function reset(){
	jQuery("#newBookId").val("");
	jQuery("#newUserId").val("");
	
	jQuery("#newName").html("");
	jQuery("#newIdcard").html("");
	jQuery("#newBookName").html("");
	jQuery("#newPrice").html("");
	jQuery("#newBorrowDate").html("");
	jQuery("#newPlanDate").html("");
	jQuery("#ispenalty").attr("checked",false);
	jQuery("#penaltyPrice").html("0");
	jQuery("#penaltyReason").val("1");
}

function configBackBook(){
	var bid = jQuery("#newBookId").val();
	var dataJson = {};
	dataJson.bid = bid;
	if (jQuery("#ispenalty").is(":checked")) {
		 reasonType = jQuery("#penaltyReason").val();
		 penaltyamount = jQuery("#penaltyPrice").html();
		 dataJson.reasonType = reasonType;
		 dataJson.penaltyamount = penaltyamount;
     }
	jQuery.ajax({
		url:'/v1/ub/saveBackBook/'+bid,
		dataType:'json',
		data:dataJson,
		type:'post',
		success:function(data){
			if(data.error){
				$.ligerDialog.error(data.msg);
			}else{
				$.ligerDialog.success('亲,还书处理成功!');
				booksBorrowsManager.loadServerData({pagesize:10});
				try{
					addBackBooksOpen.hidden();
				}catch(e){}
			}
		},error:function(){
			$.ligerDialog.error('网络错误，请稍后再试!');
		}
	});
	
}
function getTime_ToStr(time){
	
	var date = new Date();

	date.setFullYear(1970,1,1);

	date.setTime(0);

	date.setMilliseconds(time);

	var strdate = (date.getYear()+1900)   +   "年" + (date.getMonth() +1)  +   "月"   +   date.getDate()+"日";

	return strdate;

}